package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.user.dto.LoginDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.User;
import com.heima.model.user.vo.ApLoginVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @author: zhk
 * @since: 2025/6/12
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ApLoginVO login(LoginDTO loginDTO) {
        String phone = loginDTO.getPhone();
        String password = loginDTO.getPassword();
        Long id = 0L;
        ApUser apUser = new ApUser();
        if (!(phone.equals("") && password.equals(""))) {

            apUser = query().eq("phone", loginDTO.getPhone()).eq("password", loginDTO).one();
            if (apUser != null) {
                String apUserPassword = apUser.getPassword();
                String salt = apUser.getSalt();
                String passwordMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
                if (passwordMd5.equals(apUserPassword)) {
                    id = apUser.getId();
                } else {
                    throw new RuntimeException("账号密码有误");
                }
            }
        }
        String token = AppJwtUtil.getToken(id);
        User user = new User();
        BeanUtils.copyProperties(apUser, user);
        ApLoginVO apLoginVO = ApLoginVO.builder()
                .user(user)
                .token(token)
                .build();

        return apLoginVO;
    }


}
